<template>
  <div ref="main" class="main">
    <el-row>
      <el-col :span="3">
        <el-row style="margin-top: 70px">
          <el-col :span="5" style="text-align: right">
            <i class="iconfont icon-jiantouarrowhead7" @click="reduceMonth" />
          </el-col>
          <el-col :span="8" style="text-align: center">
            <span style="font-size: 25px">{{
              month[parseInt(days.split("-")[1]) - 1]
            }}</span>
          </el-col>
          <el-col :span="5" style="text-align: left">
            <i class="iconfont icon-jiantouarrowhead7-copy" @click="addMonth" />
          </el-col>
        </el-row>
        <el-row style="margin-top: 20px">
          <el-col :span="5" style="text-align: right">
            <i class="iconfont icon-jiantouarrowhead7" @click="reduceYear" />
          </el-col>
          <el-col :span="8" style="text-align: center">
            <span style="font-size: 25px">{{ days.split("-")[0] }}</span>
          </el-col>
          <el-col :span="5" style="text-align: left">
            <i class="iconfont icon-jiantouarrowhead7-copy" @click="addYear" />
          </el-col>
        </el-row>
      </el-col>
      <el-col :span="21">
        <el-row ref="scrollbarRef">
          <el-col v-for="(item, index) in num" :key="index" :class="item.isBlue" :span="3" style="
              height: 45px;
              border: 2px solid #717171;
              text-align: center;
              line-height: 45px;
              border-radius: 5px;
              font-size: 18px;
              font-weight: 700;
            ">周{{ item.num }}</el-col>
        </el-row>
        <div class="scrollbarF">
          <el-scrollbar :height="height">
            <el-row v-for="(item, index) in date" :key="index">
              <el-col v-for="(row, index1) in item" :key="index1" :span="3" style="
                  height: 88.3px;
                  border: 2px solid #717171;
                  text-align: center;
                  line-height: 45px;
                  border-radius: 5px;
                " :class="!row.colorFlag || row.colorFlag == 1
                  ? isConsent
                  : row.colorFlag == 2
                    ? isSuccess
                    : isError
                  " :style="parseInt(row.weekDate.split('-')[1]) !=
    parseInt(days.split('-')[1])
    ? 'color: #ced4db'
    : 'color: #000'
    " @click="distribution(row)">
                <el-row>
                  <el-col :span="18" style="text-align: left; padding-left: 15px">
                    <div style="
                        height: 14px;
                        margin-top: 12px;
                        line-height: 12px;
                        font-size: 14px;
                      ">
                      方案数：{{ row.projectCount || 0 }}
                    </div>
                    <div style="
                        height: 14px;
                        margin-top: 12px;
                        line-height: 12px;
                        font-size: 14px;
                      ">
                      点位数：{{ row.pointCount || 0 }}
                    </div>
                    <div style="
                        height: 14px;
                        margin-top: 12px;
                        line-height: 12px;
                        font-size: 14px;
                      ">
                      采样员：{{ row.userCount || 0 }}
                    </div>
                  </el-col>
                  <el-col :span="6" style="text-align: center">
                    <span style="font-size: 22px; font-weight: 700">{{
                      parseInt(row.day)
                    }}</span>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </el-scrollbar>
        </div>
      </el-col>
    </el-row>

    <el-dialog :class="'el-dialog-theme3'" v-model="open" :title="title" append-to-body draggable
      :close-on-click-modal="false" @close="closedDialog" width="1200">
      <el-form label-width="110px" :model="form" ref="dialogFormRef" :rules="rules">
        <el-row>
          <el-col :span="7">
            <el-form-item label="计划日期：">
              {{ parseTime(form.cyDate, "{y}年{m}月{d}日") }}
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-button link type="success" style="line-height: 2">导出采样任务单</el-button>
          </el-col>
        </el-row>
        <p class="pinformation">搜索条件</p>
        <el-form :model="searchCriteriaForm">
          <el-row :gutter="10">
            <el-col :span="7">
              <el-form-item label="点位编号：">
                <el-input v-model="searchCriteriaForm['project.projectCode']" clearable placeholder="请输入点位编号"
                  @keyup.enter="search"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="9">
              <el-form-item label="点位名称：">
                <el-input v-model="searchCriteriaForm['point.pointName']" clearable placeholder="请输入点位名称"
                  @keyup.enter="search"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="第几天：">
                <el-input v-model="searchCriteriaForm.currentDay" clearable placeholder="请输入第几天"
                  @keyup.enter="search"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="3">
              <el-row justify="end">
                <el-button type="success" @click="search">搜索</el-button>
                <el-button class="business resetBtn" @click="resetForm">重置</el-button>
              </el-row>
            </el-col>
          </el-row>
        </el-form>
        <el-row>
          <p class="pinformation">当日点位列表</p>
          <p class="totalStyle">共 {{ currentDayPointList.length }} 条数据</p>
        </el-row>
        <el-table :data="currentDayPointList" max-height="15vw" ref="currentDayPointRef" @selection-change="onAddSelect"
          row-key="cyId" v-loading="loading">
          <el-table-column type="selection" width="55" align="center" :reserve-selection="true" />
          <el-table-column prop="project.projectCode" label="方案编号" align="center" width="120" />
          <el-table-column prop="project.wtCustomName" label="委托单位" align="center" show-overflow-tooltip />
          <el-table-column prop="point.pointName" label="点位名称" align="center" width="150" show-overflow-tooltip />
          <el-table-column prop="jclbId" label="检测类型" align="center" show-overflow-tooltip width="130">
            <template #default="scope">
              {{
                proxy.getItemByArray(
                  jclbList,
                  "jclbId",
                  scope.row.jclbId,
                  "jclbName"
                )
              }}
            </template>
          </el-table-column>
          <el-table-column prop="sumDay" label="连测天数" align="center" width="90" />
          <el-table-column prop="currentDay" label="第几天" align="center" width="90" />
          <el-table-column prop="cyDate" label="计划日期" align="center" width="100" />
          <el-table-column prop="fpcyy" label="分配采样员" align="center" show-overflow-tooltip />
        </el-table>
        <el-row style="margin-top: 10px">
          <el-col :span="8">
            <el-form-item label="调整日期：" prop="sengTime">
              <el-date-picker v-model="form.sengTime" value-format="YYYY-MM-DD" :clearable="false" :editable="false"
                :picker-options="false" placeholder="调整日期" @change="sengTimeChange"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label-width="0">
              {{
                "当日已安排" +
                countForm.projectCount +
                "个方案，" +
                countForm.pointCount +
                "个点位"
              }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18">
            <el-form-item label="选择采样员：" prop="cyUserIds">
              <el-select v-model="form.cyUserIds" multiple :disabled="!form.sengTime" filterable style="width: 100%">
                <el-option v-for="item in cyUserList" :key="item.userId" :value="item.userId" :label="item.nickName">
                  <span style="float: left; margin-right: 20px">{{
                    item.nickName
                  }}</span>
                  <span style="float: right">{{ item.remark }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="2" :offset="1">
            <el-button type="success" @click="define">确定</el-button>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="danger" @click="open = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { getMonthByNextDays } from "@/api/common";
import {
  getCalendarView,
  getDialogListDate,
  getDialogUserList,
  getDialogCount,
  putDialogDate,
} from "@/api/project/projectPlan";
import { allListJclb } from "@/api/store/jclb";
const days = ref("");
const { proxy } = getCurrentInstance();
const isSuccess = ref("isSuccess");
const isError = ref("isError");
const isConsent = ref("isConsent");
const num = ref([
  { num: "一" },
  { num: "二" },
  { num: "三" },
  { num: "四" },
  { num: "五" },
  { num: "六", isBlue: "isBlue" },
  { num: "日", isBlue: "isBlue" },
]);

const month = ref([
  "一月",
  "二月",
  "三月",
  "四月",
  "五月",
  "六月",
  "七月",
  "八月",
  "九月",
  "十月",
  "十一月",
  "十二月",
]);

const date = ref([]);
const props = defineProps({
  queryParams: {
    type: Object,
  },
});
const currentDayPointList = ref([]);
const searchCriteriaForm = ref({});
const form = ref({ cyIds: [] });
const open = ref(false);
const title = ref("当日任务");
const rules = ref({
  sengTime: [{ required: true, message: "调整日期不能为空", trigger: "blur" }],
  cyUserIds: [
    { required: true, message: "分配采样员不能为空", trigger: "blur" },
  ],
});

const loading = ref(false)

const jclbList = ref([]);
allListJclb().then((res) => {
  jclbList.value = res.data;
});

defineExpose({
  getCalendar,
});

function getCalendar() {
  let temp = props.queryParams;
  temp.params.queryMonth = days.value;
  getCalendarView(temp).then((res) => {
    date.value = res.data;
  });
}

function getHeight() {
  height.value =
    window.innerHeight -
    proxy.$refs["scrollbarRef"].$el.getBoundingClientRect().top -
    proxy.$refs["scrollbarRef"].$el.scrollHeight -
    20 +
    "px";
}

function getDays() {
  getMonthByNextDays().then((res) => {
    days.value = res.data;
    getCalendar();
  });
}

function reduceYear() {
  days.value =
    parseInt(days.value.split("-")[0]) - 1 + "-" + days.value.split("-")[1];
  getCalendar();
}

function addYear() {
  days.value =
    parseInt(days.value.split("-")[0]) + 1 + "-" + days.value.split("-")[1];
  getCalendar();
}

function reduceMonth() {
  if (days.value.split("-")[1] - 1 == 0) {
    days.value = parseInt(days.value.split("-")[0]) - 1 + "-" + "12";
  } else {
    days.value =
      days.value.split("-")[0] + "-" + (parseInt(days.value.split("-")[1]) - 1);
  }
  getCalendar();
}

function addMonth() {
  if (parseInt(days.value.split("-")[1]) + 1 == 13) {
    days.value = parseInt(days.value.split("-")[0]) + 1 + "-" + "1";
  } else {
    days.value =
      days.value.split("-")[0] + "-" + (parseInt(days.value.split("-")[1]) + 1);
  }
  getCalendar();
}
onMounted(() => {
  nextTick(() => {
    getHeight();
    window.addEventListener("resize", getHeight);
  })
})
onUpdated(() => {
  getHeight();
});
onBeforeUnmount(() => {
  window.removeEventListener("resize", getHeight);
});

const height = ref();

function distribution(row) {
  if (row.projectCount === 0 || !row.projectCount) return
  form.value.cyDate = row.weekDate;
  form.value.sengTime = proxy.parseTime(row.weekDate, "{yyyy}-{mm}-{dd}");
  searchCriteriaForm.value.cyDate = proxy.parseTime(
    row.weekDate,
    "{y}-{m}-{d}"
  );
  search().then((res) => {
    proxy.$refs["currentDayPointRef"].clearSelection();
    proxy.$refs["currentDayPointRef"].toggleAllSelection();
  });
  sengTimeChange();

  open.value = true;
}

function closedDialog() {
  searchCriteriaForm.value = {};
  form.value = {
    cyIds: [],
  };
  currentDayPointList.value = [];
}

function onAddSelect(selection) {
  form.value.cyIds = selection.map((item) => {
    return item.cyId;
  });
  var previous = "";
  for (let i = 0; i < selection.length; i++) {
    let temp = "";
    let tempcyUserNames = selection[i].taskUserList.map((item1) => {
      return item1.cyUserName;
    });
    let tempUserIds = selection[i].taskUserList.map((item1) => {
      return item1.cyUserId;
    });
    temp = tempcyUserNames.join("、");
    if (previous == "") {
      previous = temp;
    }
    if (temp !== previous) {
      form.value.cyUserIds = [];
      break;
    } else {
      form.value.cyUserIds = tempUserIds;
    }
  }
  if (!selection.length) {
    form.value.cyUserIds = [];
  }
}

function search() {
  return new Promise((resolve, reject) => {
    searchCriteriaForm.value.cyDate = proxy.parseTime(
      form.value.cyDate,
      "{y}-{m}-{d}"
    );
    loading.value = true
    getDialogListDate(searchCriteriaForm.value).then((res) => {
      loading.value = false
      currentDayPointList.value = res.data;
      currentDayPointList.value.forEach((item, index) => {
        var temp = item.taskUserList.map((row) => {
          return row.cyUserName;
        });
        currentDayPointList.value[index].fpcyy = temp.join("、");
      });
      resolve();
    }).catch(() => {
      loading.value = false
    })
  });
}

const cyUserList = ref([]);

const countForm = ref({ projectCount: 0, pointCount: 0 });
function sengTimeChange() {
  cyUserList.value = [];
  countForm.value = { projectCount: 0, pointCount: 0 };
  getDialogUserList(form.value.sengTime).then((res) => {
    cyUserList.value = res.data;
  });
  getDialogCount(form.value.sengTime).then((res) => {
    countForm.value = res.data;
  });
}

function define() {
  if (form.value.cyUserIds.length == 1) {
    proxy.$modal.msgError("至少选择2个采样员！");
    return;
  }
  if (form.value.cyIds.length > 0) {
    proxy.$refs["dialogFormRef"].validate(async (valid) => {
      if (valid) {
        var temp = {
          cyDate: form.value.sengTime,
          cyUserIds: form.value.cyUserIds,
          cyIds: form.value.cyIds,
        };
        putDialogDate(temp).then((res) => {
          proxy.$modal.msgSuccess(res.msg);
          search().then((res) => {
            proxy.$refs["currentDayPointRef"].clearSelection();
            proxy.$refs["currentDayPointRef"].toggleAllSelection();
          });
          getCalendar();
        })
      }
    });
  } else {
    proxy.$modal.msgError("选择要分配的检测点位！");
  }
}

function resetForm() {
  searchCriteriaForm.value = {};
  search();
}

getDays();
</script>

<style lang="scss">
@import "../../../../assets/limsIconFont/arrowheadIconFont/iconfont.css";

.isBlue {
  color: #12be80;
}

.isSuccess {
  background-color: #d8fdde;
}

.isError {
  background-color: #fbd0d0;
}

.isConsent {
  background-color: #fff;
}

.scrollbarF .el-scrollbar__bar.is-vertical {
  right: 10.7vw;
}
</style>
